//
//  ST_ChangeAvatarManager.swift
//  btvideo
//
//  Created by mac on 2020/4/20.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SwifterSwift
import SnapKit
import KDDragAndDropCollectionViews
import HandyJSON
import TZImagePickerController
import SwiftyUserDefaults

/**头像审核中 新增选择 替换新图片审核*/
class ST_ChangeAvatarManager: NSObject {
    
    static let shared = ST_ChangeAvatarManager()
    
    private override init() {
        super.init()
        
    }
    
    fileprivate lazy var match_loading:ST_MatchFaceLoadingController = {
        
        let loading = ST_MatchFaceLoadingController()
    
        loading.overCurrentContext = true
    
        return loading
    }()
    
    weak var hud_root_controller:UIViewController?
    
    /**
     头像审核中 选项
     */
    func face_fail_match_options()  {
        
        let attrString = NSMutableAttributedString(string: "头像是你吗？")
        
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.medium),.foregroundColor: UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)]
        
           attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
           
           let attrString1 = NSMutableAttributedString(string: "伴心酱有点分不清头像照片是不是\n你，试试人工审核或者更换照片吧")
           
           let paragh = NSMutableParagraphStyle()
           paragh.alignment = .center
           let attr1: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14),.foregroundColor: UIColor(red: 0.4, green: 0.4, blue: 0.4, alpha: 1),.paragraphStyle:paragh]
           
           attrString1.addAttributes(attr1, range: NSRange(location: 0, length: attrString1.length))
           
           let alert = BTVerticalAlertViewController.init(title: attrString, message: attrString1, imageName: "头像认证疑问", confirmText: "人工审核头像", cancelText: "使用其他照片")

           alert.overCurrentContext = true
           
           alert.over_current_context_alpha = "0.4"

           alert.root_view_height = 290
           
           alert.root_view_width = 250
        
//        确定人工审核 什么都不做
            alert.confirm_closure = {
                
            }
//        换张图片 做法
            alert.cancel_closure = {[weak self] in
                self?.upload_avatar_handle()
            }
           
           GlobalPresent(toController: alert)
        
        
        
    }
    
    /**
     上传头像
     */
    func upload_avatar_handle(){
        
        guard let vc = TZImagePickerController.init(maxImagesCount: 1, delegate: self) else{ return }
        
        vc.allowPickingVideo = false
        
        self.hud_root_controller?.show_indeterminate_h_u_d()
        
        vc.didFinishPickingPhotosHandle = {[weak self] photos,assets,isSelectOriginalPhoto in
            
            if let image = photos?.first,let dt = image.pngData(){
                
               let content_key = UUID().uuidString
                
               JVUpload(fileKey: content_key, data: dt, uploadProgress: { (f) in
                   
               }, success: { (json) in
                   
                let p = ["avatar":content_key,"width":image.size.width,"height":image.size.height] as [String : Any]
                   
                self?.push_to_remote(param: p, image: image)
                   
               }) { (code, err) in
                   
                   print("上传图片失败 ")
                   
                self?.hud_root_controller?.hidden_indeterminate_h_u_d()
                
                ToastHud(text: err, view: self?.hud_root_controller?.view)
               }
            }else{
                self?.hud_root_controller?.hidden_indeterminate_h_u_d()
            }
        }
                    
        GlobalPresent(toController: vc, animated: true)
        
    }
    
    fileprivate func push_to_remote(param:[String:Any],image:UIImage){
        
        guard let avatarKey = param["avatar"] as? String else{
            self.hud_root_controller?.hidden_indeterminate_h_u_d()
            return
        }
        if FACE_AVATAE_STATE != 1{
            GlobalPresent(toController: match_loading)
        }
        
        
        JVrequest(PH.changeAvatarApi,parameters:param, success: { (json) in
            
            print("换头像返回成功:",json)
            
            self.hud_root_controller?.hidden_indeterminate_h_u_d()
            
            let status = json["data"]["face_avatar_state"].intValue
            
            let handler = {
                
                if status == 4{
                    
                    self.face_fail_match_options()
                    
                }else if status == 3{
                    
                    GlobalPresent(toController: ST_MatchFaceSuccessController())
                    
                }
                
                FACE_AVATAE_STATE = status
                
                NotificationCenter.default.post(name: NSNotification.Name.my_avatar_updated, object: nil, userInfo: ["avatarKey":avatarKey,"localImage":image])
            }
            
            
            if FACE_AVATAE_STATE != 1{
                self.match_loading.dismiss(animated: true) {
                    handler()
                }
            }else{
                handler()
            }
            
        }) { (code, err) in
            
            self.hud_root_controller?.hidden_indeterminate_h_u_d()
            
            if FACE_AVATAE_STATE != 1{
                self.match_loading.dismiss(animated: true) {
                    ToastHud(text: err, view: self.hud_root_controller?.view)
                }
            }else{
                ToastHud(text: err, view: self.hud_root_controller?.view)
            }
            print("换头像返回失败:",err)
            
        }
        
    }
}


extension ST_ChangeAvatarManager:TZImagePickerControllerDelegate{
    
    func tz_imagePickerControllerDidCancel(_ picker: TZImagePickerController!) {
        
        self.hud_root_controller?.hidden_indeterminate_h_u_d()
        
    }
    
}
